import React, {Component} from 'react';
import PubSub from "pubsub-js";

import "./index.css"

class List extends Component {
  state = {
    userList: [], // 用户列表
    isFirst: true, // 是否为第一次打开页面
    isLoading: false, // 是否是等待状态
    err: "" // 存储请求相关的错误信息
  }

  componentDidMount() {
    // 初始化数据
    this.token = PubSub.subscribe("updateState", (msg,data) => {
      this.setState(data);
    })
  }
  componentWillUnmount() {
    // 卸载监听事件
    PubSub.unsubscribe(this.token);
  }

  render() {
    const {userList, isFirst, isLoading, err} = this.state;
    return (
      <div className="row">
        {
          isFirst ? <h1>请输入关键字,随后点击搜索按键</h1> : isLoading ? '搜索中.....' : err ? <h1>{err}</h1> :
            userList.map(item => {
              return (
                <div className="card" key={item.id}>
                  <a rel="noreferrer" href={item.html_url} target="_blank">
                    <img src={item.avatar_url} style={{width: '100px'}} alt="head_portrait"/>
                  </a>
                  <p className="card-text">{item.login}</p>
                </div>
              )
            })
        }
      </div>
    );
  }
}

export default List;